import "dart:convert";

import "package:ct_pa_majordomo/config/extension.dart";
import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/privacy_policy.dart";
import "package:ct_pa_majordomo/pages/transfer_station.dart";
import "package:ct_pa_majordomo/pages/user/api.dart";
import "package:ct_pa_majordomo/pages/user/create_apartment/index.dart";
import "package:ct_pa_majordomo/pages/user/widgets/clear_text_field.dart";
import "package:ct_pa_majordomo/pages/user/widgets/code_text_field.dart";
import "package:ct_pa_majordomo/pages/user/widgets/password_text_field.dart";
import "package:ct_pa_majordomo/pages/user_agreement.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/button/tap_container.dart";
import "package:ct_pa_majordomo/widgets/button/tap_text.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/gestures.dart";
import "package:flutter/material.dart";
import "package:flutter/services.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:flutter_form_builder/flutter_form_builder.dart";
import "package:provider/provider.dart";

enum UserType { login, register, forgot }

class User extends StatefulWidget {
  final UserType type;

  const User({super.key, this.type = UserType.login});

  @override
  State<User> createState() => _UserState();
}

class _UserState extends State<User> {
  final GlobalKey<FormBuilderState> _formKey = GlobalKey<FormBuilderState>();
  late final bool _login = widget.type == UserType.login;
  late final bool _register = widget.type == UserType.register;
  late final bool _forgot = widget.type == UserType.forgot;
  String _label = "";
  bool _agreePrivacy = storage.getBool("agreePrivacy") ?? false;

  FormBuilderState? get _formState => _formKey.currentState;

  void _changeAgree() {
    bool next = !_agreePrivacy;
    storage.setBool("agreePrivacy", next);
    setState(() => _agreePrivacy = next);
  }

  void _handleSuccess() {
    EasyLoading.dismiss();
    storage.setString("phonenumber", _formState!.fields["phonenumber"]?.value ?? "");
    Stacker.pushAndRemoveUntil(const TransferStation());
  }

  Future _getApartmentInfo(commonVM) async {
    Map resData = await apartmentApi.getApartmentInfo();
    if (context.mounted) {
      print("apartInfo :>>> ${resData["data"]}");
      if (resData["data"] == null) {
        EasyLoading.dismiss();
        storage.setString("phonenumber", _formState!.fields["phonenumber"]?.value ?? "");
        Navigator.push(context, CupertinoPageRoute(builder: (context) {
          return CreateApartment();
        }));
      } else {
        storage.setString("apartment", jsonEncode(resData["data"]));
        _handleSuccess();
      }
      // if (resData["data"] == null) {
      //   EasyLoading.dismiss();
      //   Navigator.push(context, CupertinoPageRoute(builder: (context) {
      //     return CreateApartment();
      //   }));
      // } else {
      //   commonVM.setApartment(resData["data"]);
        // _handleSuccess();
      // }
    }
  }

  Future<void> _submitLogin(commonVM) async {
    await userApi.login(_formState!.value);
    await _getApartmentInfo(commonVM);
    _handleSuccess();
  }

  Future<void> _submitRegister(commonVM) async {
    await userApi.register(_formState!.value);
    EasyLoading.dismiss();
    EasyLoading.showSuccess("注册成功");
    storage.setString("phonenumber", _formState!.fields["phonenumber"]?.value ?? "");
    Stacker.pop();
  }

  void _submit(commonVM) async {
    try {
      // Navigator.pushNamed(context, "/home");
      // Stacker.pushAndRemoveUntil(const TransferStation());
      // return;
      if (!_formState!.saveAndValidate()) return;
      FocusManager.instance.primaryFocus?.unfocus();
      EasyLoading.show();
      if (_login) _submitLogin(commonVM);
      if (_register) _submitRegister(commonVM);
    } catch (error) {
      print(error);
    }
  }

  Widget _renderAgree() {
    TextStyle style = const TextStyle(
      color: ThemeVars.colorPrimary,
      decoration: TextDecoration.underline,
      decorationColor: ThemeVars.colorPrimary,
    );
    return Row(
      children: [
        TapContainer(
          width: 16,
          height: 16,
          decoration: BoxDecoration(
            border: Border.all(
              color: _agreePrivacy
                  ? ThemeVars.colorPrimary
                  : ThemeVars.colorBorder,
            ),
            borderRadius: BorderRadius.circular(100),
            color: _agreePrivacy ? ThemeVars.colorPrimary : null,
          ),
          onTap: _changeAgree,
          child: _agreePrivacy
              ? const Icon(
                  Icons.check_rounded,
                  size: 14,
                  color: Colors.white,
                )
              : null,
        ),
        Text.rich(
          TextSpan(
            children: [
              const TextSpan(text: " 我已阅读 "),
              TextSpan(
                text: "用户协议",
                style: style,
                recognizer: TapGestureRecognizer()
                  ..onTap = () => Stacker.push(const UserAgreement()),
              ),
              const TextSpan(text: " 和 "),
              TextSpan(
                text: "隐私政策",
                style: style,
                recognizer: TapGestureRecognizer()
                  ..onTap = () => Stacker.push(const PrivacyPolicy()),
              ),
              const TextSpan(text: " 并同意"),
            ],
          ),
        ),
      ],
    );
  }

  List<Widget> _renderFormItem(Widget field, [Widget? extra]) => [
        field,
        if (extra != null) ...[const SizedBox(height: 10), extra],
        const SizedBox(height: 20),
      ];

  Widget _renderForm(commonVM) {
    bool? every = _formState?.instantValue.values
        .every((value) => Utils.isNotEmpty(value));
    bool disabled = !_agreePrivacy || !(every ?? false);
    return FormBuilder(
      key: _formKey,
      onChanged: () => setState(() {}),
      child: ListView(
        padding: const EdgeInsets.all(30) + const EdgeInsets.only(top: 30),
        children: [
          const Text("阿泰管家", style: TextStyle(fontSize: 22)),
          const SizedBox(height: 20),
          Text(
            _label,
            style: const TextStyle(fontSize: 26, fontWeight: FontWeight.w500),
          ),
          const SizedBox(height: 20),
          if (!_login) ..._renderFormItem(
            ClearTextField(
              initialValue: storage.getString("nickName"),
              name: "nickName",
              decoration: const InputDecoration(hintText: "昵称"),
            ),
          ),
          ..._renderFormItem(
            ClearTextField(
              initialValue: storage.getString("phonenumber"),
              name: "phonenumber",
              decoration: const InputDecoration(hintText: "手机号"),
            ),
          ),
          ..._renderFormItem(
            const PasswordTextField(
              name: "password",
              decoration: InputDecoration(hintText: "密码"),
            ),
            _login
                ? Align(
                    alignment: Alignment.centerRight,
                    child: TapText(
                      text: "忘记密码？",
                      onTap: () =>
                          Stacker.push(const User(type: UserType.forgot)),
                    ),
                  )
                : null,
          ),
          if (!_login) ...[
            ..._renderFormItem(
              const PasswordTextField(
                name: "confirmPassword",
                decoration: InputDecoration(hintText: "确认密码"),
              ),
              const Text(
                "8-20位密码，至少含数字/字母/字符中的2种",
                style: TextStyle(color: ThemeVars.colorTextTer, fontSize: 12),
                textAlign: TextAlign.center,
              ),
            ),
            ..._renderFormItem(
              CodeTextField(sendCode: () => Future.value(true)),
            ),
          ],
          _renderAgree(),
          const SizedBox(height: 20),
          Button(
            size: ButtonSize.large,
            onPressed: disabled ? null : () => _submit(commonVM),
            child: Text(_forgot ? "设置新密码" : _label),
          ),
          const SizedBox(height: 20),
          Center(
            child: TapText(
              text: _login ? "新用户注册" : "去登录",
              onTap: _login
                  ? () => Stacker.push(const User(type: UserType.register))
                  : Stacker.pop,
            ),
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    if (_login) _label = "登录";
    if (_register) _label = "注册";
    if (_forgot) _label = "忘记密码";
  }

  @override
  Widget build(BuildContext context) {
    ThemeData themeData = Theme.of(context);
    return Theme(
      data: themeData.copyWith(
        inputDecorationTheme: themeData.inputDecorationTheme.copyWith(
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(100)),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(100),
            borderSide: BorderSide.none,
          ),
          filled: true,
          fillColor: ThemeVars.colorBackground,
        ),
      ),
      child: AnnotatedRegion<SystemUiOverlayStyle>(
        value: SystemUiOverlayStyle.dark,
        child: Scaffold(
          backgroundColor: ThemeVars.colorPrimaryLight,
          body: Container(
            margin: const EdgeInsets.all(10) + MediaQuery.paddingOf(context),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(30),
              color: Colors.white,
            ),
            child: Consumer<CommonState>(builder: (ctx, commonVM, child) {
              return _renderForm(commonVM);
            })
          ),
        ),
      ),
    );
  }
}
